import React, { useState } from 'react';
import { Card, Form, Input, Button, Radio, message } from 'antd';
import logo from '../../assets/logo192.png';
import './index.css';
import LoginStore from '../../store/login';
import useStore from '../../store';
import { useNavigate } from 'react-router-dom'
const Item = Form.Item

const Login = () => {
  const navigate = useNavigate()
  const { LoginStore } = useStore()
  
  // 获取表单数据
  const onFinish = async(values) =>{
    const { mobile,code,remember } = values
    console.log(values);
    localStorage.clear();
    try {
      // 登录 
      await LoginStore.getToken ({mobile,code,remember})
      // 跳转首页
      if (remember==1) {
        navigate('/Layoutstudent/home',{replace:true})
        localStorage.setItem('studentid', mobile);
      }else if (remember==2) {
        navigate('/Layoutteacher/home',{replace:true})
        localStorage.setItem('teacherid', mobile);
      }else if (remember==3) {
        navigate('/Layoutadmin/home',{replace:true})
        localStorage.setItem('adminid', mobile);
      }
      // 提示用户登录成功
      message.success('登录成功！')
    } catch (error) {
      message.error(error.response?.data.message || '登录失败')
    }

  }
  return (
    <div className='login'>
       <h1 style={{ textAlign: 'center', color: '#FFFFFF', fontSize: '48px', marginTop: '100px' }}>学生课程管理系统</h1>
      <Card className='login-container'>
        <img src={logo} alt="图片" className='login-logo' />
        {/* 登录表单 */}
        <Form validateTrigger={['onBlur','onChange']} onFinish={onFinish} initialValues={{remember:1}}>
          <Item name='mobile' rules={[
            { required:true,message:'请输入学号或者工号' },
            {
              validateTrigger:'onBlur', // 设置触发时机失去焦点时触发
              message:'请输入学号或者工号' }
          ]} label="账号：">
            <Input size='large' placeholder='请输入学号或者工号' />
          </Item> 
          <Item name='code' rules={[
            { required:true,message:'请输入密码,初始密码为身份证后六位' },
            { 
              validateTrigger:'onBlur',
              message:'请输入密码,初始密码为身份证后六位' }
          ]} label="密码：">
            <Input size='large' type='password' placeholder='请输入密码' />
          </Item>
          <Item
              name="remember"
              label="选择你的登录身份："  // 添加 label 属性，用于显示在表单项之前
             rules={[{ required: true, message: '请选择你的登录身份' }]}>  
            <Radio.Group>
              <Radio value={1}>学生</Radio>
              <Radio value={2}>老师</Radio>
              <Radio value={3}>管理员</Radio>
            </Radio.Group>
          </Item>
          <Item>
            <Button type='primary' htmlType='submit' size='large' block>登录</Button>
          </Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
